package cn.com.cetccst.appshield;

import static cn.com.cetccst.appshield.worker.CheckBlackAppsWorker.DATA_CONFIG;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.work.BackoffPolicy;
import androidx.work.Data;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import cn.com.cetccst.appshield.worker.CheckBlackAppsWorker;
import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.PolicyEntity;
import cn.com.cetccst.datacenter.policy.type.BlackWhiteAppSetting;
import cn.com.cetccst.tools.log.CommonLogger;

public class AppShieldManager {
    private static AppShieldManager instance;
    private final LiveData<PolicyEntity> entity;

    private final MutableLiveData<BlackWhiteAppSetting> blackWhiteAppSetting = new MutableLiveData<>();
    private final WorkManager workManager;

    public static void initialize(Context context) {
        if (instance == null) {
            instance = new AppShieldManager(context);
        }
    }

    public static AppShieldManager getInstance() {
        return instance;
    }

    private AppShieldManager(Context context) {

        workManager = WorkManager.getInstance(context);
        entity = PolicyRepository.getInstance().getPolicy(PolicyEntity.POLICY_BLACK_WHITE_SETTING);
        //动态监听合规性策略的变化，从而驱动UI和事件的执行
        entity.observeForever(policyEntity -> {
            CommonLogger.info("load black white app settings data from DB ");
            if (policyEntity != null) {
                String blackwhiteSetting = null;
                try {
                    JSONObject settingObj = new JSONObject(policyEntity.getContent());
                    blackwhiteSetting = settingObj.optString("config");
                } catch (JSONException e) {
                    CommonLogger.error("parse black white policy error", e);
                    throw new RuntimeException(e);
                }
                BlackWhiteAppSetting setting = new Gson().fromJson(blackwhiteSetting, BlackWhiteAppSetting.class);
                blackWhiteAppSetting.setValue(setting);

                Data data = new Data.Builder()
                        .putString(DATA_CONFIG, blackwhiteSetting)
                        .build();

                PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(
                        CheckBlackAppsWorker.class,
                        Duration.ofMinutes(15))
                        .setBackoffCriteria(
                                BackoffPolicy.LINEAR,
                                Duration.ofMinutes(5))
                        .setInputData(data)
                        .build();

//                workManager.cancelUniqueWork("FORBID_BLACK_APP");
                workManager.enqueueUniquePeriodicWork(
                        "FORBID_BLACK_APP",
                        ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE,
                        periodicWork);
            } else {
                workManager.cancelUniqueWork("FORBID_BLACK_APP");
            }
        });
    }

    public LiveData<BlackWhiteAppSetting> getBlackWhiteAppSetting() {
        return blackWhiteAppSetting;
    }

}
